package com.lagou.sqlSession;

import com.lagou.pojo.Configuratioin;
import com.lagou.pojo.MappedStatement;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;
import com.lagou.utils.TokenHandler;
import sun.misc.Perf;

import javax.sql.DataSource;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Author: yw
 * @Date: 2021/7/25 11:00
 **/
public class SimpleExecutor implements Executor {
    @Override
    public <E> List<E> query(Configuratioin configuratioin, MappedStatement mappedStatement, Object... params) throws Exception {
//       //1获取链接
//        Connection connection = configuratioin.getDataSource().getConnection();
//
//       //2获取sql 并且转换sql
//        String sql = mappedStatement.getSql();
//        BoundSql boundSql = getBoundSql(sql);
//
//        //3预处理对象 :
//        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqText());
//
//        //参数设置
//        String paramType = mappedStatement.getParamType();
//        Class<?> paramTypeClass = getType(paramType);
//        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
//        for(int i = 0;i < parameterMappings.size();i++){
//            ParameterMapping parameterMapping = parameterMappings.get(i);
//            String content = parameterMapping.getContent();
//            //利用反射
//            Field declaredField = paramTypeClass.getDeclaredField(content);
//            declaredField.setAccessible(true);
//            Object o = declaredField.get(params[0]);
//            preparedStatement.setObject(i+1,o);
//        }
        //执行sql
        ResultSet resultSet = paramToPreparedStatement(configuratioin, mappedStatement, params).executeQuery();
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getType(resultType);

        List<Object> objects = new ArrayList<>();
        //封装结果集
        while (resultSet.next()){
            ResultSetMetaData metaData = resultSet.getMetaData();
            Object o = resultTypeClass.newInstance();
            for(int i = 1; i <= metaData.getColumnCount(); i++){

                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);

                //使用反射或者内省，根据数据库和实体对应关系，
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName,resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o,value);

            }
            objects.add(o);
        }
        return (List<E>) objects;
    }

    @Override
    public int saveOrUpdate(Configuratioin configuratioin, MappedStatement mappedStatement, Object... params) throws Exception{

        int rows = paramToPreparedStatement(configuratioin, mappedStatement, params).executeUpdate();
        return rows;
    }

    private PreparedStatement paramToPreparedStatement(Configuratioin configuratioin, MappedStatement mappedStatement, Object... params) throws Exception{
        //1获取链接
        Connection connection = configuratioin.getDataSource().getConnection();

        //2获取sql 并且转换sql
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        //3预处理对象 :
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqText());

        //参数设置
        String paramType = mappedStatement.getParamType();
        Class<?> paramTypeClass = getType(paramType);
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        for(int i = 0;i < parameterMappings.size();i++){
            ParameterMapping parameterMapping = parameterMappings.get(i);
            String content = parameterMapping.getContent();
            //利用反射
            Field declaredField = paramTypeClass.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i+1,o);
        }

        return preparedStatement;
    }

    /**
     * 完成对#{}的解析工作， 1 将#{}使用？代替， 2 解析出来的#{}里面的值进行存储
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql){
        //标记处理类：配合标记解析器完成对占位符的处理
        TokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parse = genericTokenParser.parse(sql);
        //#{}里面解析出来的参数名称
        List<ParameterMapping> parameterMappings = ((ParameterMappingTokenHandler) parameterMappingTokenHandler).getParameterMappings();
        BoundSql boundSql = new BoundSql(parse,parameterMappings);

        return boundSql;
    }

    private Class<?> getType(String paramType) throws ClassNotFoundException {
        if(null != paramType){
            Class<?> aClass = Class.forName(paramType);
            return aClass;
        }

        return null;
    }
}
